/*
 * Copyright 2018-2021 guerlab.net and other contributors.
 *
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.guerlab.smart.pay.service.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import net.guerlab.smart.pay.core.searchparams.NotifyOriginalLogSearchParams;
import net.guerlab.smart.pay.service.entity.NotifyOriginalLog;
import net.guerlab.smart.pay.service.mapper.NotifyOriginalLogMapper;
import net.guerlab.smart.pay.service.service.NotifyOriginalLogService;
import net.guerlab.smart.platform.server.service.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 通知原始记录服务实现
 *
 * @author guer
 */
@Slf4j
@Service
public class NotifyOriginalLogServiceImpl extends BaseServiceImpl<NotifyOriginalLog, Long, NotifyOriginalLogMapper, NotifyOriginalLogSearchParams>
        implements NotifyOriginalLogService {

    private ObjectMapper objectMapper;

    @Async
    @Override
    public void add(String payChannel, Object originalData, String result) {
        payChannel = StringUtils.trimToNull(payChannel);
        if (payChannel == null) {
            return;
        }

        NotifyOriginalLog entity = new NotifyOriginalLog();
        entity.setNotifyOriginalLogId(sequence.nextId());
        entity.setCreateTime(LocalDateTime.now());
        entity.setPayChannel(payChannel);
        entity.setResult(result);
        try {
            entity.setContent(objectMapper.writeValueAsString(originalData));
            getBaseMapper().insert(entity);
        } catch (Exception e) {
            log.debug(e.getLocalizedMessage(), e);
        }
    }

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }
}
